<?php

class UserController extends Controller {

	/**
	 * @return array action filters
	 */
	public function filters () {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules () {
		return array(
			array('allow', // allow all users to perform 'index' and 'view' actions
				'actions' => array('index', 'register', 'login', 'view', 'admin'), //'resendEmail', 'verify',
				'users' => array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions' => array('logout', 'update', 'AddCart', 'DisplayCart', 'DeleteCart'),
				'users' => array('@'),
			),
			array('deny', // deny all users
				'users' => array('*'),
			),
		);
	}

        public function actionAddCart ($id, $quantity) {
            $this->render('AddCart', array("id" => $id, "quantity" => $quantity));

        }

        public function actionDisplayCart () {
            $this->render('DisplayCart');
        }

        public function actionDeleteCart ($id) {
            $item = array("id" => $id);
            $this->render('DeleteCart', $item);
        }

	/**
	 * Registers a new user.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionRegister () {
		$model = new User;
		if (isset($_POST['User'])) {
			$post = $model->attributes = $_POST['User'];

			if ($model->save()) {
				$loginForm = new LoginForm;
				$loginForm->email = $post['email'];
				$loginForm->password = $post['password'];
				$loginForm->login();
				$this->redirect(Yii::app()->user->returnUrl);
			}

			$model->password = '';
		} else if (isset($_POST['signed_request'])) {
			$response = explode('.', $_POST['signed_request']);
			$response = CJSON::decode(base64_decode($response[1]), true);
			$userInfo = $response['registration'];
			$model->attributes = $userInfo;
			if ($model->save()) {
				$loginForm = new LoginForm;
				$loginForm->email = $userInfo['email'];
				$loginForm->password = $userInfo['password'];
				$loginForm->login();
				$this->redirect(Yii::app()->user->returnUrl);
			}
		}
		$this->render('register', array(
			'model' => $model,
		));
	}

	/**
	 * Handles login.
	 */
	public function actionLogin () {
		$model = new LoginForm;

		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			if ($model->validate() && $model->login()) {
				$this->redirect(isset($_GET['redirect']) ? $_GET['redirect'] : Yii::app()->homeUrl);
			}
		}
		$model->password = '';

		$this->render('login', array('model' => $model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout () {
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	/**
	 * Displays the User's profile page.
	 * @param integer $id the ID of the User to be displayed.
	 */
	public function actionView ($id) {
		$model = $this->loadModel($id);
		$dataProvider = new CActiveDataProvider('Item', array(
			'criteria' => array(
				'condition' => "user_id = $model->id"
			),
			'pagination' => array(
				'pageSize' => 12
			)
		));
		$this->render('view', array(
			'user' => $model,
			'dataProvider' => $dataProvider,
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate ($id) {
		$model = $this->loadModel($id);

		if (isset($_POST['User'])) {
			$model->attributes = $_POST['User'];
			if ($model->save())
				$this->redirect(array('view', 'id' => $model->id));
		}

		$this->render('update', array(
			'model' => $model,
		));
	}

	/**
	 * Returns the data model based on the either the primary key or username.
	 * They will be redirected to the username URL if they requested with the
	 * primary key.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded.
	 * @return User the loaded User.
	 */
	public function loadModel ($id) {
		$model = User::model()->findByPk($id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}

		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation ($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
